/*
 *  Copyright (c) 2022 ZhuHai Jieli Technology Co.,Ltd.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include "gpio.h"

#define     DEBUG_UART  JL_UART2
static u8 used_tx_io;

__attribute__((always_inline_when_const_args)) int putchar(int a)
{
    if (DEBUG_UART->CON0 & BIT(0)) {
        DEBUG_UART->BUF = a;
        __asm__ volatile("csync");
        while ((DEBUG_UART->CON0 & BIT(15)) == 0);
        DEBUG_UART->CON0 |= BIT(13);
    }
    return 1;
}
static void uart_set_baud(u32 baud)
{
    DEBUG_UART->CON0 &= ~BIT(0);
    DEBUG_UART->CON0 |= BIT(13) | BIT(12) | BIT(10);
    DEBUG_UART->BAUD = (clk_get("uart") / baud) / 4 - 1;
    DEBUG_UART->CON0 |= BIT(13) | BIT(12) | BIT(10) | BIT(0);
}

void uart_init(void)
{
    char *tx_pin = "PA10";

    JL_IOMAP->CON3 &= ~BIT(7);
    gpio_output_channle(get_gpio(tx_pin), CH1_UT2_TX);
    JL_UART1->CON0 = BIT(13) | BIT(12) | BIT(10);
    uart_set_baud(115200);
    used_tx_io = get_gpio(tx_pin);
}
__attribute__((always_inline_when_const_args)) void uart_close(void)
{
    if (DEBUG_UART->CON0 & BIT(0)) {
        DEBUG_UART->CON0 = 0;
        DEBUG_UART->CON1 = 0;
    }
}
